package main.http;

/**
 * Created by hdt3213 on 17/3/27.
 */

import main.tcp.TcpApp;
import main.tcp.TcpServer;
import java.util.HashMap;

import java.io.IOException;

public class HttpHandler implements TcpApp {

	TcpServer server;
	HashMap<String, String> router = new HashMap<String, String>();
	static StaticCache cache = new StaticCache();
	static String staticPrefix = "/static/";

	@Override
	public void setServer(TcpServer server) {
		this.server = server;
	}

	@Override
	public void setup() {

	}

	@Override
	public void onMsg(String address, String msg) {
		try {
			HttpResponse response;
			HttpRequest request;

//			System.out.println(msg);

			request = new HttpRequest(msg);
			request.parse();

			if (request.getPath().startsWith(staticPrefix)) {
				response = handleStatic(request);
			}
			else {
				response = handle(request);
			}

			server.send(address, response.getTxt());
		}
		catch (Exception e) {
			e.printStackTrace();
		}

	}


	// override this method to implement your app
	public HttpResponse handle(HttpRequest request) {
		HttpResponse response = new HttpResponse();
		response.setStatus(404);
		return response;
	}


	public HttpResponse handleStatic(HttpRequest request) {
		return cache.get(request.getPath());
	}

	public void clean() {

	}

	@Override
	public void onClose(String address) {

	}

}
